layui.define(['table', 'jquery', 'form'], function(exports) {
    const MOD_NAME = 'selectHelper'
    const $ = layui.jquery
    const table = layui.table
    const form = layui.form

    class selectHelper {
        constructor() {
            this.listenFilter = ''
            this.reqUrl = ''
            this.reqParam = {}
            this.reqKey = 'id'
            this.targetId = ''

            // <option value="value">label</option>
            this.resp = {
                value: 'id',
                label: 'title',
            }
        }

        // 实例化一个对象
        clone() {
            return new selectHelper()
        }

        //
        setListenFilter(filter) {
            this.listenFilter = filter
            return this
        }

        setReqUrl(url, param) {
            param = param || {}
            this.reqUrl = url
            if(JSON.stringify(param)!=="{}") {
                this.reqParam = param
            }
            return this
        }

        setReqParam(param) {
            for(let k in param) {
                this.reqParam[k] = param[k]
            }
            return this
        }

        setReqKey(key) {
            this.reqKey = key
            return this
        }

        setResp(value, label) {
            this.resp.value = value
            this.resp.label = label
            return this
        }

        setTargetId(targetId) {
            this.targetId = targetId
            return this
        }

        eventBind(data) {
            const that = this
            const val = data.value

            // 获取数据
            const param = this.reqParam
            param[this.reqKey] = val
            const url = this._buildUrl(this.reqUrl, param)

            $.getJSON(url, function(d) {
                if(d.code !== 0) {
                    layer.msg(d.msg)
                    return false
                }

                const objSelect = $('#' + that.targetId)
                objSelect.html('')
                const data = d.data

                for(let i = 0; i<data.length; i++) {
                    const line = data[i]
                    const option = $('<option>').val(line[that.resp.value]).text(line[that.resp.label])
                    objSelect.append(option)
                }

                form.render('select')
            })
        }

        run() {
            // 绑定事件
            const that = this
            form.on('select('+ this.listenFilter +')', function(data) {
                that.eventBind(data)
            })
        }

        _buildUrl(url, param) {
            let paramStr = ''
            for(let key in param) {
                paramStr += '&' + key + '=' + param[key]
            }
            if(url.indexOf('?') === -1 && !!paramStr) {
                url += '?'
            }
            return url + paramStr
        }
    }


    const obj = new selectHelper();
    exports(MOD_NAME, obj)
});